import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/device_detail_controller.dart';
import '../../../data/constants/alarm_type_icon.dart';
import '../../../widgets/safe_network_image.dart';

class AlarmHistoryWidget extends GetView<DeviceDetailController> {
  final Function(String) onTap;

  AlarmHistoryWidget({super.key, required this.onTap});

  // 滚动控制器
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    // 移除自动滚动功能

    return Column(
      children: [
        // 告警历史顶部栏
        _buildAlarmTopBar(),

        // 告警列表内容
        Expanded(
          child: Obx(() {
            if (controller.isLoadingAlarms.value &&
                controller.alarmList.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(color: Color(0xFF047FF7)),
                    SizedBox(height: 20.h),
                    Text(
                      '正在加载数据...',
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: Color(0xFF999999),
                      ),
                    ),
                  ],
                ),
              );
            }

            if (controller.alarmList.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 空状态图片
                    Image.asset(
                      'assets/images/null.png',
                      width: 378.w,
                      height: 378.w,
                    ),
                    SizedBox(height: 40.w),
                    Text(
                      '暂无告警记录',
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: const Color(0xFF999999),
                      ),
                    ),
                  ],
                ),
              );
            }

            return RefreshIndicator(
              onRefresh: controller.refreshAlarmHistory,
              color: Color(0xFF047FF7),
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification scrollInfo) {
                  if (scrollInfo.metrics.pixels ==
                          scrollInfo.metrics.maxScrollExtent &&
                      controller.hasMoreAlarms.value &&
                      !controller.isLoadingAlarms.value) {
                    controller.loadMoreAlarmHistory();
                  }
                  return false;
                },
                child: ListView.builder(
                  controller: _scrollController, // 添加滚动控制器
                  padding: EdgeInsets.all(32.w),
                  itemCount:
                      controller.alarmList.length +
                      (controller.hasMoreAlarms.value ? 1 : 0),
                  itemBuilder: (context, index) {
                    if (index == controller.alarmList.length) {
                      // 加载更多指示器
                      return Container(
                        padding: EdgeInsets.all(32.w),
                        child: Center(
                          child: CircularProgressIndicator(
                            color: Color(0xFF047FF7),
                          ),
                        ),
                      );
                    }
                    final alarm = controller.alarmList[index];
                    return _buildAlarmItem(alarm);
                  },
                ),
              ),
            );
          }),
        ),
      ],
    );
  }

  /// 构建告警历史顶部栏
  Widget _buildAlarmTopBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.h),
      child: Row(
        children: [
          // 左侧：告警消息 + 未读数
          Expanded(
            child: Row(
              children: [
                Icon(
                  Icons.warning_outlined,
                  size: 36.sp,
                  color: Color(0xFF047FF7),
                ),
                SizedBox(width: 12.w),
                Text(
                  '告警消息',
                  style: TextStyle(
                    fontSize: 28.sp,
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(width: 16.w),
                GestureDetector(
                  onTap: controller.markAllAlarmsRead,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 8.h,
                    ),
                    decoration: BoxDecoration(
                      color: Color(0xFF047FF7),
                      borderRadius: BorderRadius.circular(16.r),
                    ),
                    child: Text(
                      '一键已读',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 右侧：日期选择
          GestureDetector(
            onTap: () {
              _showAlarmDatePicker();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 16.h),
              decoration: BoxDecoration(
                color: Color(0xFFF8F9FA),
                borderRadius: BorderRadius.circular(16.r),
                border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.calendar_today_outlined,
                    size: 32.sp,
                    color: Color(0xFF047FF7),
                  ),
                  SizedBox(width: 8.w),
                  Obx(() {
                    final now = DateTime.now();
                    final selectedDate = controller.selectedAlarmDate.value;
                    final isToday =
                        selectedDate.year == now.year &&
                        selectedDate.month == now.month &&
                        selectedDate.day == now.day;
                    return Text(
                      isToday ? '今日' : controller.formattedAlarmDate,
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.w500,
                      ),
                    );
                  }),
                  SizedBox(width: 6.w),
                  Icon(
                    Icons.keyboard_arrow_down,
                    size: 28.sp,
                    color: Color(0xFF999999),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示告警日期选择器
  void _showAlarmDatePicker() {
    DateTime tempSelectedDate = controller.selectedAlarmDate.value;

    Get.bottomSheet(
      Container(
        height: 520.h,
        decoration: BoxDecoration(
          color: CupertinoColors.systemBackground,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              height: 100.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                color: CupertinoColors.systemBackground,
                border: Border(
                  bottom: BorderSide(
                    color: CupertinoColors.separator,
                    width: 0.5.w,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () => Get.back(),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: CupertinoColors.systemBlue,
                      ),
                    ),
                  ),
                  Text(
                    '选择告警日期',
                    style: TextStyle(
                      fontSize: 34.sp,
                      fontWeight: FontWeight.w600,
                      color: CupertinoColors.label,
                    ),
                  ),
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      controller.selectAlarmDate(tempSelectedDate);
                      Get.back();
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: CupertinoColors.systemBlue,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // iOS风格日期选择器 - 只选择年月日
            Expanded(
              child: Container(
                color: CupertinoColors.systemBackground,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: controller.selectedAlarmDate.value,
                  minimumDate: DateTime(2020, 1, 1),
                  maximumDate: DateTime.now(),
                  onDateTimeChanged: (DateTime date) {
                    tempSelectedDate = date;
                  },
                  dateOrder: DatePickerDateOrder.ymd, // 年-月-日顺序
                ),
              ),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  /// 构建告警项
  Widget _buildAlarmItem(Map<String, dynamic> alarm) {
    final String alarmIcon =
        alarmTypeIconMap[alarm['alarmType'] ?? 0] ??
        'assets/images/device/list/1.png';

    // 获取当前告警的索引
    final alarmIndex = controller.alarmList.indexOf(alarm);

    return GestureDetector(
      onTap: () async {
        // 选择当前告警
        controller.selectAlarm(alarmIndex);

        // ✅ 点击告警项时立即调用已读接口
        final msgId = alarm['id']?.toString();
        if (msgId != null) {
          // 判断是否为未读状态
          final readStatus = alarm['readStatus'];
          final read = alarm['read'];
          final isUnread =
              (readStatus != 1 && readStatus != null) ||
              (read != true && read != null) ||
              (readStatus == null && read == null);

          // 如果是未读状态，立即标记为已读
          if (isUnread) {
            print('📖 点击告警项，立即标记为已读: $msgId');
            controller.markAlarmRead(msgId);
          }
        }

        // ✅ selectAlarm 方法现在会自动播放对应的视频
        // 如果告警项没有视频，selectAlarm 会处理停止当前视频的逻辑
      },
      child: Obx(() {
        final isSelected = controller.selectedAlarmIndex.value == alarmIndex;
        return Container(
          margin: EdgeInsets.only(bottom: 24.h),
          padding: EdgeInsets.all(32.w),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFFF0F8FF) : Colors.white,
            borderRadius: BorderRadius.circular(20.r),
            border:
                isSelected
                    ? Border.all(color: const Color(0xFF047FF7), width: 2.w)
                    : null,
            boxShadow: [
              BoxShadow(
                color:
                    isSelected
                        ? const Color(0xFF047FF7).withValues(alpha: 0.1)
                        : Colors.black.withValues(alpha: 0.04),
                offset: const Offset(0, 2),
                blurRadius: 8,
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 告警类型图片 - 带未读红点标识
              Stack(
                clipBehavior: Clip.none,
                children: [
                  Container(
                    width: 45,
                    height: 45,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Image.asset(
                      alarmIcon,
                      fit: BoxFit.contain,
                      width: 45,
                      height: 45,
                    ),
                  ),
                  // 未读消息小红点标识
                  if ((alarm['readStatus'] != 1 &&
                          alarm['readStatus'] != null) ||
                      (alarm['read'] != true && alarm['read'] != null) ||
                      (alarm['readStatus'] == null && alarm['read'] == null))
                    Positioned(
                      top: -4.h,
                      right: -4.w,
                      child: Container(
                        width: 12.w,
                        height: 12.h,
                        decoration: const BoxDecoration(
                          color: Color(0xFFFF0202),
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                ],
              ),
              SizedBox(width: 20.w),
              // 告警信息和时间
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 告警信息
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            alarm['alarmTypeName']?.toString() ??
                                alarm['alarmName']?.toString() ??
                                '报警消息',
                            style: TextStyle(
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w500,
                              color: const Color(0xFF333333),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 12.h),
                    // 时间
                    Text(
                      _formatAlarmTime(
                        alarm['alarmTime']?.toString() ??
                            alarm['time']?.toString(),
                      ),
                      style: TextStyle(
                        fontSize: 22.sp,
                        color: const Color(0xFF999999),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 20.w),
              // 视频缩略图封面
              Builder(
                builder: (context) {
                  // 尝试多个可能的字段名
                  final pictureUrl = alarm['alarmPicture']?.toString() ??
                      alarm['picUrl']?.toString() ??
                      alarm['picture']?.toString() ??
                      '';
                  
                  return Container(
                    width: 180.w,
                    height: 135.h,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12.r),
                      color: const Color(0xFFF0F0F0),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12.r),
                      child: pictureUrl.isNotEmpty
                          ? Stack(
                              children: [
                                // 使用安全的网络图片加载
                                SafeNetworkImage(
                                  imageUrl: pictureUrl,
                                  width: double.infinity,
                                  height: double.infinity,
                                  fit: BoxFit.cover,
                                  errorWidget: Image.asset(
                                    'assets/images/暂无视频2x.png',
                                    width: double.infinity,
                                    height: double.infinity,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                                Center(
                                  child: Icon(
                                    Icons.play_circle_outline,
                                    size: 40,
                                    color: Colors.white54,
                                  ),
                                ),
                              ],
                            )
                          : Image.asset(
                              'assets/images/暂无视频2x.png',
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.cover,
                            ),
                    ),
                  );
                },
              ),
            ],
          ),
        );
      }),
    );
  }

  /// 格式化告警时间 - 显示年月日时分秒 yyyy-MM-dd HH:mm:ss 格式
  String _formatAlarmTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '时间未知';

    try {
      final dateTime = DateTime.parse(timeStr);
      // 转换为北京时间 (UTC+8)
      final beijingTime = dateTime.toUtc().add(const Duration(hours: 8));
      // 格式化为 yyyy-MM-dd HH:mm:ss 格式（包含秒数）
      return '${beijingTime.year}-${beijingTime.month.toString().padLeft(2, '0')}-${beijingTime.day.toString().padLeft(2, '0')} ${beijingTime.hour.toString().padLeft(2, '0')}:${beijingTime.minute.toString().padLeft(2, '0')}:${beijingTime.second.toString().padLeft(2, '0')}';
    } catch (e) {
      // 如果解析失败，返回原始时间字符串
      return timeStr;
    }
  }
}
